<!-- 1、当延迟执行resolve的时候，状态一直没有由pending转换成其他状态，所以需要在then的时候处理peding状态，
把成功或者失败的时候的回调函数存储起来，当状态变化的时候再取出执行
2、需要定义两个数组，一个成功回调的数组，一个失败回调的数组 -->

<script>
  const PENDING = 'pending'
  const FULFILLED = 'fulfilled'
  const REJECTED = 'rejected'
  class MyPromise {
    constructor(executor) {
      this.state = PENDING
      this.result = undefined
      this.resolveCallbacks = []
      this.rejectCallbacks = []
      const resolve = (result) => {
        if (this.state === PENDING) {
          this.state = FULFILLED
          this.result = result
          this.resolveCallbacks.forEach((callback) => {
            callback(result)
          })
        }
      }
      const reject = (result) => {
        if (this.state === PENDING) {
          this.state = REJECTED
          this.result = result
          this.rejectCallbacks.forEach((callback) => {
            callback(result)
          })
        }
      }
      executor(resolve, reject)
    }

    then(onFulfilled, onRejected) {
      onFulfilled =
        typeof onFulfilled === 'function' ? onFulfilled : (value) => value
      onRejected =
        typeof onRejected === 'function'
          ? onRejected
          : (reason) => {
              throw reason
            }
      if (this.state === FULFILLED) {
        onFulfilled(this.result)
      }
      if (this.state === REJECTED) {
        onRejected(this.result)
      }
      if (this.state === PENDING) {
        this.resolveCallbacks.push(onFulfilled)
        this.rejectCallbacks.push(onRejected)
      }
    }
  }

  const p1 = new MyPromise((resolve, reject) => {
    setTimeout(() => {
      resolve(1)
    },2000)
  })
  p1.then((res) => {
    console.log(res)
  })
</script>
